// 页面基类
module.exports = Behavior({
    properties: {},
    data: {
        /**
         * 检查用户手机号
         */
        checkMobile: false,
        checkwxAuth: false, //是否授权手机号
        showWxAuth: false, //手机号授权弹框
        toLogin: true, //跳转商家登录
        host: 'https://www.yunanhua.com',//正式
        // host: 'https://flower.justdoget.cn',//测试
        imgHost: 'https://img.yunanhua.com',
        uid: "",
        userInfo: { //用户数据
            uid: '',
            /**0:待审核,1:通过认证,2:认证被拒绝,3未提交 */
            supplier_verify: 3,
            nickname: '',
            face: '',
            /**积分 */
            points: 0,
        },
        contact: {
            tel: '400-'
        }, //联系客服电话，微信，坐标 
        /**客户端来源，数据请求时，头部标记
         * express 员工端
         */
        client: '',
        wxshowModal: false,
        pay:"allin",
        payType:1,
        whDetail:{},//仓库信息
        payTypeArr:[],//根据仓库信息配置支付方式
    },
    created: function () {},
    attached: function () {},
    ready: function () {

        this.data.userInfo = getApp().globalData.userInfo;
        // console.log('基类 ready', this.data.userInfo);
        this.check_mobile();
    },

    methods: {
        onLoad: function (options) {
            // console.log('基类 onload');
            this.data.userInfo = getApp().globalData.userInfo;
        },
        //跳转收银台--通联支付
        alinePay(extraData,okfunc=null){
            wx.navigateToMiniProgram({
                appId: 'wxef277996acc166c3',
                extraData: {
                    ...extraData
                },
                success() {
                    console.log('成功打开通联小程序');
                    okfunc && okfunc();
                }
            })
            // wx.openEmbeddedMiniProgram({
            //     appId: 'wxef277996acc166c3',
            //     extraData: {
            //         ...extraData
            //     },
            //     success() {
            //         console.log('成功打开通联小程序');
            //         okfunc && okfunc();
            //     }
            // })
        },
        onPhoneauth(e) {
            console.log("授权手机号", e)
            if (e.detail == 0) {
                wx.showToast({
                    title: '请授权获取手机号',
                    icon: "none"
                })
            } else {
                let userInfo = getApp().globalData.userInfo
                userInfo.wx_auth = 1
                getApp().globalData.userInfo = userInfo
                this.setData({
                    showWxAuth: false
                })
            }
        },
        /**检查用户是否已经完善手机资料 */
        check_mobile() {
            let userInfo = this.data.userInfo
            if (this.data.checkMobile) { //检查用户是否已经绑定手机号等信息
                // console.log("checkMobile")
                if (!userInfo || !userInfo.uid) { //用户未登录，则执行登陆操作
                    // console.log("未登陆，先登录");
                    this.getUserInfo();
                } else if (!userInfo.mobile_bind) { //未绑定手机，跳转绑定页面
                    wx.showModal({
                        content: '请完善资料',
                        showCancel: true,
                        title: '完善资料',
                        success: (result) => {
                            if (result.confirm) {
                                // console.log("跳转完善页面");
                                wx.navigateTo({
                                    url: '/pages/cls/updateInfo/Index?type=1',
                                })
                            } else {
                                // console.log("取消完善");
                                wx.switchTab({
                                    url: '/pages/cls/index/index'
                                })
                            }
                        },

                    })
                }
            }
            if (this.data.checkwxAuth) { //检查授权绑定手机号
                // console.log("userInfo",userInfo)
                if (!userInfo || !userInfo.uid) { //用户未登录，则执行登陆操作
                    // console.log("未登陆，先登录");
                    this.getUserInfo();
                } else if (userInfo.mobile_bind == 0 && userInfo.wx_auth == 0) { //未绑定手机且未授权
                    this.setData({
                        showWxAuth: true
                    })
                }
            }
        },
        /**登陆状态更新之后重载的方法 */
        login_reload() {
            console.log("执行基类重载方法")
            this.data.userInfo = getApp().globalData.userInfo;
        },
        /**拨打客服电话 */
        call_phone(e) {
            // e.currentTarget
            wx.makePhoneCall({
                phoneNumber: e.currentTarget.dataset.tel || getApp().globalData.config1.mobile
            })
        },
        /**隐藏弹窗通用方法 */
        hide_popup(e) {
            let obj = {};
            obj[e.currentTarget.dataset.field] = false;
            this.setData(obj)
        },
        /**显示弹窗通用方法 */
        show_popup(e) {
            let obj = {};
            obj[e.currentTarget.dataset.field] = true;
            this.setData(obj)
        },
        /**
         * 获取完整的缩略图地址
         * @param {string} url 
         * @param {string} type  缩略图大小，默认small,中图wide
         */
        get_thumb(url, type = 'small') {
            let thumb = '/assets/common/logo.png';
            if (url) {
                thumb = this.data.imgHost + '/' + url + '!' + type;
            }
            return thumb
        },
        //获取当前仓库的支付方式1微信，2通联
        getPayType(id) {
            this.request({
                url: this.data.host + '/home/index/warehouse/info',
                data: {
                    wh_id: id,
                }
            }, res => {
                var data = res.data
                var payTypeArr=[]
                if(data.is_main_wh_pay){
                    payTypeArr.push({
                        title:"钱包支付",
                        name:"coin",
                        icon:"/assets/qianbaoPay.png"
                    })
                }

                var pay = "allin"
                if (data.pay_type == 1) {
                    //微信支付
                    pay = 'wxpay'
                    payTypeArr.push({
                        title:"微信支付",
                        name:"wxpay",
                        icon:"/assets/weixinzhifu.png"
                    })
                } else {
                    //通联支付
                    pay = 'allin'
                    payTypeArr.push({
                        title:"微信支付",
                        name:"allin",
                        icon:"/assets/weixinzhifu.png"
                    })
                }
                console.log("payTypeArr",payTypeArr)
                this.setData({
                    pay: pay,
                    payType: data.pay_type,
                    whDetail:data,
                    payTypeArr:payTypeArr
                })
                this.successPayOrderWh()
            });
        },
        successPayOrderWh(){},
        //选择支付方式
        onClickPayType(event) {
            let name = event.currentTarget.dataset.name;
            // this.data.payData.code = name;
            this.setData({
                pay: name,
            })
        },
        // 微信登陆
        getUserInfo() {
            let that = this;
            console.log("uidBasePage", that.data.uid)
            // return;
            wx.login({
                withCredentials: true,
                timeout: 10000,
                success(res) {
                    if (res.code) {
                        let code = res.code;
                        that.request({
                            method: 'GET',
                            url: that.data.host + '/home/login',
                            data: {
                                code: code,
                                invite_id: that.data.uid
                            }
                        }, res => {
                            // wx.showToast({
                            //   title: '登陆成功',
                            // })
                            wx.setStorageSync('Authorization', res.data.access_token)
                            that.data.userInfo = getApp().globalData.userInfo = res.data;
                            console.log("登陆成功，检测用户资料状态", res);
                            that.check_mobile();
                            that.login_reload()
                        });


                    } else {
                        wx.showToast({
                            icon: 'none',
                            title: '登录失败！' + res.errMsg,
                        })
                    }
                },
                fail(res) {
                    wx.showToast({
                        icon: 'none',
                        title: res.errMsg || '获取微信授权失败',
                    })
                }
            })
        },
        /**
         * 获取用户信息(头像，昵称等)
         */
        getUserProfile() {
            console.log("getUserProfile");
            let that = this;
            let userInfo = this.data.userInfo;
            wx.showModal({
                content: '请授权完善头像，昵称等信息！',
                showCancel: true,
                title: '完善信息',
                success: (result) => {
                    if (result.confirm) {
                        wx.navigateTo({
                            url: "/pages/cls/updateInfo/Index?type=2",
                        })
                        // wx.getUserProfile({
                        //   desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
                        //   success: (user) => {
                        //     that.request({
                        //       url: that.data.host + '/home/user/audit',
                        //       data: {
                        //         face: user.userInfo.avatarUrl,
                        //         nickname: user.userInfo.nickName,
                        //         sex: user.userInfo.gender
                        //       },
                        //       method: "POST",
                        //     }, () => {
                        //       userInfo.face = user.userInfo.avatarUrl;
                        //       userInfo.nickname = user.userInfo.nickName;
                        //       userInfo.sex = user.userInfo.gender;
                        //       that.setData({
                        //         userInfo
                        //       })
                        //     })
                        //   }
                        // })
                    }
                },
            })
        },
        /**
         * 网络请求封装
         * @param {*} req_data  
         * url 请求地址,
         * loadingTip:加载中提示，如果存在，先显示loading
         * @param {*} success_func 成功回调方法
         * @param {*} fail_func 失败回调方法,code 不为零时也会调用
         * @param {*} complete 最终执行的方法
         */
        request: function (req_data, success_func, fail_func = null, complete = null) {
            let that = this;
            let Authorization = wx.getStorageSync('Authorization');

            if (req_data.loadingTip) {
                wx.showLoading({
                    title: req_data.loadingTip,
                    mask: true
                })
            }
            req_data.header = {
                'content-type': 'application/json',
                'client': this.data.client,
                'authtoken': wx.getStorageSync('authToken'),
                'Accept': 'application/json, text/javascript, */*; q=0.01'
            };

            if (Authorization) {
                req_data.header.Authorization = Authorization;
            }
            req_data.success = function (res) { //成功处理
                if (res.statusCode == 200) {
                    if (res.header.Authorization) {
                        wx.setStorage({
                            data: res.header.Authorization,
                            key: 'Authorization',
                        })
                    }
                    let data = res.data;
                    if (data.code == 0) {
                        success_func(data.result || data);
                    } else {
                        if (fail_func) {
                            return fail_func(data);
                        }
                        wx.showModal({
                            showCancel: false,
                            content: data.result || data.msg + "" || data.message + "",
                        })

                    }
                } else if (res.statusCode == 401) {
                    //进行登陆
                    if (that.data.wxshowModal) return
                    that.setData({
                        wxshowModal: true
                    })
                    wx.showModal({
                        content: '请先授权登陆',
                        showCancel: true,
                        title: '登陆提示',
                        complete: (res) => {
                            that.setData({
                                wxshowModal: false
                            })
                        },
                        success: (result) => {

                            if (result.confirm) {

                                console.log("invite_id", that.data.uid);
                                wx.login({
                                    success: (loginRes) => {
                                        // console.log("loginRes",loginRes);
                                        //code 登陆
                                        wx.request({
                                            url: that.data.host + "/home/login?code=" + loginRes.code + "&invite_id=" + that.data.uid,
                                            success: (res1) => {
                                                let user = res1.data;
                                                // console.log("res1",res1);
                                                wx.showToast({
                                                    title: '登陆成功',
                                                })
                                                wx.setStorageSync('Authorization', user.data.access_token)
                                                that.data.userInfo = getApp().globalData.userInfo = user.data;
                                                console.log("that.userInfo.audit", that.data.userInfo);
                                                if (!that.data.userInfo.audit) {
                                                    console.log("that.getUserProfile()");

                                                    that.getUserProfile();
                                                }
                                                that.login_reload()
                                            },
                                            fail: (e) => {
                                                // console.log(e);
                                                wx.showToast({
                                                    title: e.errMsg || '网络异常',
                                                    icon: 'none'
                                                })
                                            },
                                        })
                                    },
                                    fail: (e) => {
                                        // console.log("wx.login失败", e);
                                        wx.showToast({
                                            title: e.errMsg || '没有授权成功',
                                            icon: 'none'
                                        })
                                    },
                                })
                            }
                        },
                    })
                } else if (res.statusCode == 402) { //商家未登录状态，跳转至登录页
                    if (that.data.toLogin) {
                        that.setData({
                            toLogin: false
                        })
                        wx.showModal({
                            content: '请重新登陆',
                            showCancel: true,
                            title: '登陆提示',
                            success: (result) => {
                                if (result.confirm) {
                                    that.setData({
                                        toLogin: true
                                    })
                                    wx.navigateTo({
                                        url: '/pages/business/login/index',
                                    })
                                }
                            },
                        })
                    }

                    // wx.showToast({
                    //   title: '请重新登陆',
                    //   icon: 'none'
                    // });

                } else {
                    // console.log("res.statusCode", res.statusCode);
                    if (fail_func) {
                        return fail_func(res);
                    }
                    wx.showModal({
                        showCancel: false,
                        content: res.data.message || res.data || "网络异常",
                    })

                }
            };
            req_data.fail = function (e) { //失败处理
                fail_func ? fail_func(e) : wx.showModal({
                    showCancel: false,
                    content: '网络异常：' + e.errMsg
                });

            }
            req_data.complete = function (e) { //失败处理
                req_data.loadingTip ? wx.hideLoading() : '';
                complete ? complete(e) : '';
            }
            wx.request(req_data);
        },

    }
})